package com.solotiger.geographic.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.solotiger.geographic.R;
import com.solotiger.geographic.ui.base.BaseActivity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TestActivity extends BaseActivity {

    private TextView textView;

    private String url = "http://dili.bdatu.com/jiekou/mains/p1.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("测试");
        getToolbar().setBackgroundResource(R.color.white);
        getToolbar().setTitleTextColor(getResources().getColor(R.color.black));
        getToolbar().setNavigationIcon(R.drawable.back);
        setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        textView = (TextView) findViewById(R.id.text);

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_scrolling;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_test, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_rxjava: {
                textView.setText("");
                rxjava();
                break;
            }
            case R.id.menu_http: {
                textView.setText("");
                testHttp();
                break;
            }
            case R.id.menu_okhttp: {
                textView.setText("");
                okhttp();
                break;
            }
        }
        return true;
    }

    private void rxjava() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("hello");
                emitter.onNext("RxJava");
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())        //执行在io线程
                .observeOn(AndroidSchedulers.mainThread())//回调在主线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addText("onSubscribe");
                    }

                    @Override
                    public void onNext(String value) {
                        addText("onNext:" + value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        addText("onError=" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        addText("onComplete()");
                    }
                });

    }


    private void addText(String msg) {
        if (textView != null) {
            textView.setText(textView.getText() + msg + "\n");
        }
    }

    private void testHttp() {
        try {
            Observable.just(url)
                    .map(new Function<String, String>() {

                        @Override
                        public String apply(String url) throws Exception {
                            return get(url);
                        }
                    }).subscribeOn(Schedulers.io())        //执行在io线程
                    .observeOn(AndroidSchedulers.mainThread())//回调在主线程
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String s) throws Exception {
                            addText(s);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * HttpURLConnection实现方式
     */
    private String get(String myurl) throws IOException {
        InputStream is = null;
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            is = conn.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while (-1 != (len = is.read(buffer))) {
                baos.write(buffer, 0, len);
                baos.flush();
            }
            return baos.toString("utf-8");

        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    private void okhttp() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
//            Response response = client.newCall(request).execute();
            client.newCall(request).enqueue(
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String content = response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    addText(content);
                                }
                            });
                        }
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
